"use strict";

/**
 * @ngdoc function
 * @name jgappApp.controller:UserdefinedChoosepersonCtrl
 * @description
 * # UserdefinedChoosepersonCtrl
 * Controller of the jgappApp
 */
angular
  .module("jgappApp")
  .controller("UserdefinedChoosepersonCtrl", function(
    openApi,
    PagingService,
    Util,
    $rootScope,
    localStorageService
  ) {
    var vm = this;
    $rootScope.userArr = [];
    this.confirm = function() {
      console.log($rootScope.userArr);
      localStorageService.set("chooseUsrs", {
        aduitUserNames: getNames(),
        aduitUserIds: getuserIds()
      });
      $rootScope.userArr = [];
      Util.goBack();
    };
    var getNames = function() {
     var names= $rootScope.userArr
        .map(function(item) {
          return item.name;
        });
      return  names.join();
    };
    var getuserIds = function() {
        var ids= $rootScope.userArr
        .map(function(item) {
          return item.userId;
        })
      return  ids.join();
    };
    this.selectpeople = function(userObj) {
      if (userObj.selected) {
        userObj.flag = 1;
        $rootScope.userArr.push(userObj);
      } else {
        userObj.flag = 0;
        $rootScope.userArr = $rootScope.userArr.filter(function(item, index) {
          return item.userId != userObj.userId;
        });
      }
      $rootScope.$broadcast("userArrchange");
    };
    var merageData = function(data) {
      if (vm.userids.length == 0) {
        return;
      }
      vm.userids.forEach(function(peoitem) {
        data.forEach(function(item) {
          if (item.userId == peoitem) {
            item.selected = true;
            $rootScope.userArr.push(item);
          }
        });
      });
      $rootScope.$broadcast("userArrchange");
    };
    this.initData = function() {
      var userids = localStorageService.get("chooseUsrs") || "";
      vm.userids = [];
      if (userids) {
        vm.userids = userids.split(",");
      }
      vm.peoplelist = new PagingService(openApi.getPageListByAccount, {
        limit: 300,
        callback: merageData
      });
    };
    this.initData();
  });
